package sdk.org.apache.shiro.G2_使用.C10_SpringBoot集成_1登录和退出.AppConfig.config;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator;
import org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import sdk.org.apache.shiro.G2_使用.C10_SpringBoot集成_1登录和退出.shiro.MyShiroRealm;
import sdk.org.apache.shiro.G2_使用.C10_SpringBoot集成_1登录和退出.shiro.RedisShiroSessionDAO;
import sdk.org.apache.shiro.utils.ShiroUtils;

@Configuration
public class ShiroConfiguration {
    // 安全管理器
    @Bean("securityManager")
    public org.apache.shiro.mgt.SecurityManager securityManager() {
        // 会话ID生成器
        JavaUuidSessionIdGenerator sessionIdGenerator = new JavaUuidSessionIdGenerator();
        
        // 会话DAO
        RedisShiroSessionDAO sessionDAO = new RedisShiroSessionDAO();
        sessionDAO.setSessionIdGenerator(sessionIdGenerator);
        
        // 会话验证调度器
        QuartzSessionValidationScheduler sessionValidationScheduler = new org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler();
        sessionValidationScheduler.setSessionValidationInterval(30 * 60 * 1000);
        
        // 会话Cookie模板
        Cookie sessionIdCookie = new org.apache.shiro.web.servlet.SimpleCookie("sid");
        sessionIdCookie.setHttpOnly(true);
        sessionIdCookie.setMaxAge(180000);
        
        // 会话管理器
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setGlobalSessionTimeout(60 * 60 * 1000);  // 设置session过期时间为1小时(单位：毫秒)，默认为30分钟
        sessionManager.setDeleteInvalidSessions(true);
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        sessionManager.setSessionValidationSchedulerEnabled(true);
        sessionManager.setSessionValidationScheduler(sessionValidationScheduler);
        sessionManager.setSessionDAO(sessionDAO);
        sessionManager.setSessionIdCookieEnabled(true);
        sessionManager.setSessionIdCookie(sessionIdCookie);
        sessionValidationScheduler.setSessionManager(sessionManager);
        
        // 密码匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName(ShiroUtils.HASH_ALGORITHM);
        credentialsMatcher.setHashIterations(ShiroUtils.HASH_ITERATIONS);
        credentialsMatcher.setStoredCredentialsHexEncoded(false);
        
        // Realm实现
        AuthorizingRealm realm = new MyShiroRealm();
        realm.setCredentialsMatcher(credentialsMatcher);
//        <property name="cachingEnabled" value="true"/>
//        <property name="authenticationCachingEnabled" value="true"/>
//        <property name="authenticationCacheName" value="authenticationCache"/>
//        <property name="authorizationCachingEnabled" value="true"/>
//        <property name="authorizationCacheName" value="authorizationCache"/>
        
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        securityManager.setSessionManager(sessionManager);
        
        SecurityUtils.setSecurityManager(securityManager);
        
        return securityManager;
    }   
    
    
    //Filter工厂，设置对应的过滤条件和跳转条件
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(org.apache.shiro.mgt.SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);
        shiroFilter.setLoginUrl("/login/page");   // 登录
        
//        shiroFilter.setFilters(filters);
        
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/webjars/**", "anon");
        filterMap.put("/login/**",      "anon");
        filterMap.put("/error",         "anon");
        filterMap.put("/",              "anon");
        filterMap.put("/favicon.ico",   "anon");
        // S0004_TitanAPI 通用接口平台
        filterMap.put("/titan/monitor/**",      "anon");
        filterMap.put("/titan/view/cache",      "anon");
        filterMap.put("/titan/api",             "anon");
        //登出
        filterMap.put("/logout",                "logout");
        //对所有用户认证
        filterMap.put("/**",                    "authc");
        shiroFilter.setFilterChainDefinitionMap(filterMap);
        return shiroFilter;
    }
    
    
    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
        proxyCreator.setProxyTargetClass(true);
        return proxyCreator;
    }

    //加入注解的使用，不加入这个注解不生效
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}
